//
//  DealerEditInfoVc.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/25.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "DealerEditInfoVc.h"
#import "config.h"
#import "LocPickView.h"
#import "CompanyInfoEditView.h"
#import "UserInfoData.h"
#import "DealerDataManage.h"
#import "BdTV.h"
#import "UIButton+WebCache.h"

#import "PhootSelecteView.h"
#import "VPImageCropperViewController.h"
#import "Tools.h"




@interface DealerEditInfoVc ()<UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,VPImageCropperDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *contenView;
@property (weak, nonatomic) IBOutlet UITextField *nickEt;
@property (weak, nonatomic) IBOutlet UITextField *companyNameEt;
@property (weak, nonatomic) IBOutlet UITextField *rzEt;
@property (weak, nonatomic) IBOutlet UITextField *mobileEt;
@property (weak, nonatomic) IBOutlet UITextField *emailEt;
@property (weak, nonatomic) IBOutlet UITextField *phoneEt;
@property (weak, nonatomic) IBOutlet UIButton *addressBtn;

@property (weak, nonatomic) IBOutlet UITextField *detailLocEt;

@property (weak, nonatomic) IBOutlet UIButton *companyInfoBtn;



@property (weak, nonatomic) IBOutlet UITextField *userIdEt;

@property (weak, nonatomic) IBOutlet UITextField *codeEt;


@property (nonatomic,strong)BdTV *title;
@property (nonatomic,assign)Boolean isEditMod;
@property (nonatomic,strong) LocPickView *locateView;
@property (nonatomic,strong) CompanyInfoEditView *editView;

@property (weak, nonatomic) IBOutlet UIButton *headerImg;
@property (nonatomic,strong)PhootSelecteView *menuView;

@property DealerDataManage *dm;


@end

@implementation DealerEditInfoVc
@synthesize locateView,editView,isEditMod,title,menuView,dm;





- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    
}



-(void)initView{
    [super initView];
    
    dm = [[DealerDataManage alloc]init];
    isEditMod = false;
    
//    for (UIView *subView in self.contenView.subviews) {
//        [subView setUserInteractionEnabled:false];
//    }
    
    title = [[BdTV alloc]initWithFrame:CGRectMake(0, 0, PMW, 44)];
    [title.backBtn setTag:11];
    [title.backBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    [title.doneBtn setHidden:YES];
    [title setMianTitle:@"信息管理"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:title];
    
    
    
    
    [self.nickEt setTintColor:[UIColor redColor]];
    [self.companyNameEt setTintColor:[UIColor redColor]];
    [self.rzEt setTintColor:[UIColor redColor]];
    [self.mobileEt setTintColor:[UIColor redColor]];
    [self.emailEt setTintColor:[UIColor redColor]];
    [self.phoneEt setTintColor:[UIColor redColor]];
    [self.detailLocEt setTintColor:[UIColor redColor]];
    
    self.nickEt.delegate =self;
    self.companyNameEt.delegate =self;
    self.rzEt.delegate =self;
    self.mobileEt.delegate =self;
    self.emailEt.delegate =self;
    self.phoneEt.delegate =self;
    self.detailLocEt.delegate =self;
    
    
    
    UserInfoData *data = [DealerDataManage getUserInfo];
    
    [self.nickEt setText:data.nickName];
    [self.companyNameEt setText:data.companyName];
    [self.rzEt setText:data.validateName];
    [self.mobileEt setText:data.mobile];
    [self.emailEt setText:data.mail];
    [self.phoneEt setText:data.tell];
    [self.detailLocEt setText:data.address];
    [self.companyInfoBtn setTitle:data.companyInfo forState:UIControlStateNormal];
    
    [self.codeEt setText:data.agencyCode];
    [self.userIdEt setText:data.account];
   
    [self.headerImg setBackgroundColor:NoImgColor];
    [self.headerImg sd_setBackgroundImageWithURL:[NSURL URLWithString:data.headImgUrl] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headtop_pic"]];
}



-(void)saveUserData{
    
    UserInfoData *user = [[UserInfoData alloc]init];
    [user setNickName:[self checkString:self.nickEt.text]];
    [user setCompanyName:[self checkString:self.companyNameEt.text]];
    [user setMobile:[self checkString:self.mobileEt.text]];
    [user setMail:[self checkString:self.emailEt.text]];
    [user setTell:[self checkString:self.phoneEt.text]];
//    [user setPostCode:[self checkString:[locateView getQuCode]]];
    [user setAddress:[self checkString:self.addressBtn.titleLabel.text]];
    [user setCompanyInfo:[self checkString:self.companyInfoBtn.titleLabel.text]];
    
    [MBProgressHUD showMessage:@"保存中..."];
    
    DealerDataManage *dm2 = [[DealerDataManage alloc]init];
    [dm2 upUserInfo:user withCallBack:^(ResulteMod *resultMod) {
        
        [MBProgressHUD hideHUD];
        
        if (resultMod.resltState ==ResultNetError) {
            
            [MBProgressHUD showError:@"网络出错"];
            
        }else if (resultMod.resltState==ResultFail){
            
            [MBProgressHUD showError:[NSString stringWithFormat:@"网络出错%@",resultMod.resultCode]];
            
        }else{
            
            [MBProgressHUD showSuccess:@"保存成功"];
        }
    }];
    
}



-(NSString*)checkString:(NSString*)str{
    
    if (!str) {
        str = @"";
    }
    return str;
}


- (IBAction)addressBtnOnClick:(id)sender {
    
    if (locateView==nil) {
        locateView = [LocPickView creadInstance];
        [locateView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view endEditing:YES];
    
    [self viewRest];
    
    [locateView showInView:self.view];
}


- (IBAction)companyInfoBtnOnClick:(id)sender {
    
    if (editView==nil) {
        editView = [CompanyInfoEditView creadInstance];
        [editView.finishBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [self.view endEditing:YES];
    [self viewRest];
    [editView setText:self.companyInfoBtn.titleLabel.text];
    [editView showInView:self.view];
}

-(void)headerImgOnClick:(UIButton *)sender
{
    if (sender==menuView.tackPicBtn) {
        
        // 跳转到相机
        NSUInteger sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
    }else if(sender==menuView.selectePicBtn){
        
        // 跳转到相册
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }

    
}


//上传头像
-(void)upImg:(UIImage*)img{
    
    [menuView hide];
    
    [dm upHeadImg:img View:self.headerImg];
}




#pragma mark  UiPickView delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    image = [Tools fixOrientation:image];
    
    int h = [Tools getHightDifPMsW:100/2 sh:100/2 nw:PMW];
    CGRect buf = CGRectMake(0, PMH/2-h/2,PMW, h);
    
    // 裁剪
    VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:image cropFrame:buf limitScaleRatio:6];
    imgEditorVC.delegate = self;
    [self presentViewController:imgEditorVC animated:YES completion:^{}];
    
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}





#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)image {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
    
    image = [Tools imageWithImageSimple:image scaledToSize:CGSizeMake(100, 100)];
    
    [self upImg:image];
}



- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
}


-(void)btnOnclick:(UIButton*)sender{
    
    if(sender.tag==11){
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if(sender.tag==22){
        
        
        [self viewRest];
        
        
        if (isEditMod) {//保存
            
            [self saveUserData];
            
            isEditMod = false;
            [[title doneBtn]setTitle:@"编辑" forState:UIControlStateNormal];
            
            for (UIView *subView in self.contenView.subviews) {
                [subView setUserInteractionEnabled:false];
            }
            
        }else{
            isEditMod = true;
            [[title doneBtn]setTitle:@"保存" forState:UIControlStateNormal];
            for (UIView *subView in self.contenView.subviews) {
                [subView setUserInteractionEnabled:true];
            }
        }
    }else if(sender==locateView.sureBtn) {
        [locateView hide];
        
        [self.addressBtn setTitle:[locateView getAddress] forState:UIControlStateNormal];
    }else if(sender==editView.finishBtn){
        
        [editView hide];
        
        [self.companyInfoBtn setTitle:editView.getText forState:UIControlStateNormal];
    }
}





- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    
    CGRect dd =  [textField convertRect:textField.frame toView:self.view];
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-250-tvbotY;
    
    if (mid<0) {
        
        const float movementDuration = 0.3f;
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        CGRect buf = self.view.frame;
        buf.origin.y = up ? mid : 0;
        [self.view setFrame:buf];
        
        [UIView commitAnimations];
    }else if(up==false){
        
        [self viewRest];
    }
}



-(void)viewRest{
    
    
    if ([locateView isShow]) {
        [locateView hide];
    }
    if ([editView isShow]) {
        [editView hide];
    }
    
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.view.frame;
    buf.origin.y =  64;
    [self.view setFrame:buf];
    
    [UIView commitAnimations];
}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self animateTextField:textField up:false];
    
    [textField resignFirstResponder];
    
    [self viewRest];
    return  YES;
}

#pragma mark 换头像
- (IBAction)checkHeaderImg:(id)sender {
    
    NSLog(@"00000");
    if (self.menuView==nil) {
        menuView = [PhootSelecteView creadInstance];
        [menuView.tackPicBtn addTarget:self action:@selector(headerImgOnClick:) forControlEvents:UIControlEventTouchUpInside];
        [menuView.selectePicBtn addTarget:self action:@selector(headerImgOnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    [menuView showInView:self.view];

    
    
}


@end
